import { Controller, Inject, Post, Body, Get, Query, Put, Del } from '@midwayjs/core';
import { ExcalidrawService } from '../service/excalidraw.service';
import { IExcalidrawAttach, IExcalidrawAttachCreateOptions } from '../interface/excalidraw.interface';
import * as fs from 'fs';
import * as path from 'path';
import { v4 as uuidv4 } from 'uuid';

/**
 * Excalidraw附件控制器
 */
@Controller('/excalidraw')
export class ExcalidrawController {
  @Inject()
  excalidrawService: ExcalidrawService;

  /**
   * 获取知识库的Excalidraw附件
   * @param knowledgeId 知识库ID
   */
  @Get('/getByKnowledgeId')
  async getExcalidrawAttachByKnowledgeId(@Query('knowledgeId') knowledgeId: string) {
    try {
      const id = parseInt(knowledgeId, 10);
      if (isNaN(id)) {
        return { success: false, message: '无效的知识库ID' };
      }

      const attach = await this.excalidrawService.getExcalidrawAttachByKnowledgeId(id);
      return { success: true, data: attach };
    } catch (error) {
      console.error('获取Excalidraw附件失败:', error);
      return { success: false, message: '获取Excalidraw附件失败' };
    }
  }

  /**
   * 保存Excalidraw附件
   * @param options 创建参数
   */
  @Post('/save')
  async saveExcalidrawAttach(@Body() body: { knowledgeId: number, jsonContent: string, imageData?: string }) {
    try {
      const { knowledgeId, jsonContent, imageData } = body;
      
      // 确保存储目录存在
      const staticDir = path.join(process.cwd(), 'public', 'excalidraw');
      if (!fs.existsSync(staticDir)) {
        fs.mkdirSync(staticDir, { recursive: true });
      }
      
      // 生成唯一文件名
      const jsonFileName = `${uuidv4()}.json`;
      const jsonFilePath = path.join(staticDir, jsonFileName);
      
      // 保存JSON文件
      fs.writeFileSync(jsonFilePath, jsonContent);
      
      // 构建URL路径
      const jsonUrl = `/public/excalidraw/${jsonFileName}`;
      
      // 保存图片（如果有）
      let imageUrl = null;
      if (imageData) {
        const imageFileName = `${uuidv4()}.png`;
        const imageFilePath = path.join(staticDir, imageFileName);
        
        // 从Base64保存图片
        const base64Data = imageData.replace(/^data:image\/\w+;base64,/, '');
        fs.writeFileSync(imageFilePath, Buffer.from(base64Data, 'base64'));
        
        imageUrl = `/public/excalidraw/${imageFileName}`;
      }
      
      // 保存到数据库
      const options: IExcalidrawAttachCreateOptions = {
        knowledge_id: knowledgeId,
        excalidraw_json_url: jsonUrl,
        image_url: imageUrl
      };
      
      const id = await this.excalidrawService.createExcalidrawAttach(options);
      
      return { 
        success: true, 
        data: { 
          id, 
          excalidraw_json_url: jsonUrl,
          image_url: imageUrl 
        } 
      };
    } catch (error) {
      console.error('保存Excalidraw附件失败:', error);
      return { success: false, message: '保存Excalidraw附件失败' };
    }
  }

  /**
   * 更新Excalidraw附件
   * @param attach 附件信息
   */
  @Put('/update')
  async updateExcalidrawAttach(@Body() attach: IExcalidrawAttach) {
    try {
      if (!attach.id) {
        return { success: false, message: '附件ID不能为空' };
      }

      const success = await this.excalidrawService.updateExcalidrawAttach(attach);
      if (success) {
        return { success: true, message: '更新成功' };
      } else {
        return { success: false, message: '附件不存在' };
      }
    } catch (error) {
      console.error('更新Excalidraw附件失败:', error);
      return { success: false, message: '更新Excalidraw附件失败' };
    }
  }

  /**
   * 删除Excalidraw附件
   * @param id 附件ID
   */
  @Del('/delete')
  async deleteExcalidrawAttach(@Query('id') id: string) {
    try {
      const attachId = parseInt(id, 10);
      if (isNaN(attachId)) {
        return { success: false, message: '无效的附件ID' };
      }

      const success = await this.excalidrawService.deleteExcalidrawAttach(attachId);
      if (success) {
        return { success: true, message: '删除成功' };
      } else {
        return { success: false, message: '附件不存在' };
      }
    } catch (error) {
      console.error('删除Excalidraw附件失败:', error);
      return { success: false, message: '删除Excalidraw附件失败' };
    }
  }
}